<script setup lang='ts'>
import { Search } from '@element-plus/icons-vue'
import { useAddSave, useGetPricTree, usePricDel, useUpdate } from '@fl/api/man-api/pricing-tool'
import { useMessage } from '@fl/hooks/web/use-message'
import { cloneDeep } from 'lodash-es'
import { computed, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { initPage } from '../constant'
import AddRule from './add-rule.vue'
import AddStats from './add-stats.vue'

const router = useRouter()
const { query } = useRoute()

const { createConfirmModal, createMessage } = useMessage()

const caderRef = ref()
const addDiglog = ref(false)
const filterText = ref('')
const treeRef = ref<any>()
const editInfo = ref<any>({})

const initAddState = {
    categoryName: '', // 目录名称
    parentId: '', // 父类id
    sort: 0,
}
// 新增类目表单
const addForm = ref<any>(cloneDeep(initAddState))
const tablePage = ref<any>(cloneDeep(initPage))

// 当前选中树节点
const selected = ref<any>({})

const statsRef = ref()
const ruleRef = ref()

const isEdit = computed(() => addForm.value?.id)

const params = computed(() => ({ categoryId: query?.id || '' }))
const { data: list, isLoading, refetch } = useGetPricTree(params)

const treeData = computed(() => {
    return list.value ? [list.value] : []
})

const rules = computed(() => {
    const categoryName = [{ message: '请输入名称', required: true, trigger: 'blur' }]
    const parentId = [{ message: '请选择', required: true, trigger: 'blur' }]
    return isEdit.value ? { categoryName } : { categoryName, parentId }
})

// 新增类目表单配置
const addCol = [
    {
        fieldProps: {
            maxlength: 20,
            showWordLimit: true,
        },
        label: '名称',
        prop: 'categoryName',
        // tooltip: '名称最多显示6个字符',
        valueType: 'copy',
    },
    {
        label: '上级菜单',
        prop: 'parentId',
        valueType: 'select',
    },
    {
        fieldProps: { maxlength: 10, min: 1, precision: 0, step: 1 },
        label: '排序',
        prop: 'sort',
        valueType: 'input-number',
    },
]

function handleNodeClick(data: any) {
    // 校验是否存在未提交属性
    let hasDraft = false
    if (selected.value.level === 1 && statsRef.value?.hasDraft) { // 属性
        hasDraft = statsRef.value.hasDraft()
    }
    if (selected.value.level !== 1 && ruleRef.value?.hasDraft) { // 规则
        hasDraft = ruleRef.value.hasDraft()
    }

    if (hasDraft) {
        ElMessageBox.confirm('存在未保存修改，切换将丢失，是否继续切换?', '提示', { type: 'warning' })
            .then(() => {
                selected.value = data
                tablePage.value = cloneDeep(initPage)
            }).catch(() => {
                // 重置tree选中样式
                treeRef.value.setCurrentKey(selected.value.id)
            })
    }
    else {
        selected.value = data
        tablePage.value = cloneDeep(initPage)
    }
}

// 目录新增 编辑保存
const { mutate: mutateAddMenu } = useAddSave()
const { mutate: mutateEditMenu } = useUpdate()
function saveMenu() {
    const target = caderRef.value.getCheckedNodes() // 获取新增级联菜单数据
    const { level, path } = target[0]?.data ?? editInfo.value // 编辑数据

    const params = {
        ...addForm.value,
        path,
    }

    if (params?.id) {
        // 编辑 level 不变
        mutateEditMenu(params, {
            onSuccess: () => afterSave(),
        })
    }
    else {
        mutateAddMenu({
            ...params,
            level: level + 1,
        }, {
            onSuccess: () => afterSave(),
        })
    }
}

function afterSave() {
    queryMenu()
    addDiglog.value = false
    createMessage.success('操作成功')
}

// 查询类目 清除缓存id
async function queryMenu() {
    await refetch()

    // 重置选中
    selected.value.id = ''
}

function addMenu() {
    // 重置表单
    addForm.value = cloneDeep(initAddState)

    // 回显当前选中目录
    addForm.value.parentId = selected.value.id

    addDiglog.value = true
}

function doEditMenu(row: any) {
    editInfo.value = row
    addDiglog.value = true
    const { categoryName, id, parentId = '' } = row

    // 数据回显
    addForm.value = {
        categoryName,
        id,
        parentId,
    }
}

// 删除类目
const { mutate: mutateMenuDel } = usePricDel()
function doDelMenu(data: any) {
    if (data.children.length) {
        createMessage.error('当前存在子目录，禁止删除')
        return
    }
    createConfirmModal({
        content: '是否确认删除？',
        onSuccess: () => {
            mutateMenuDel({ categoryId: data.id }, {
                onSuccess: () => {
                    createMessage.success('操作成功')
                    queryMenu()
                },
            })
        },
    })
}

function filterNode(value: string, data: any) {
    if (!value)
        return true
    return data.categoryName.includes(value)
}

function goToList() {
    router.push('/operations-pages/pricing-tool/config-index')
}

function doCancel() {
    // 清空树形菜单
    selected.value = {}
    // 重置tree选中样式
    treeRef.value.setCurrentKey(null)
}

watch(filterText, (val) => {
    treeRef.value!.filter(val)
})
</script>

<template>
    <el-button mb-20
               @click="goToList"
    >
        返回列表
    </el-button>

    <div class="flex justify-between">
        <ElCard class="min-w-300 w-20%">
            <ElButton class="el-button el-button--primary el-button--default mb-10 w-full"
                      @click="addMenu"
            >
                新建类目
            </ElButton>

            <ElInput v-model="filterText"
                     :prefix-icon="Search"
                     class="w-full"
            />

            <el-tree ref="treeRef"
                     v-loading="isLoading"
                     :data="treeData"
                     class="py-10"
                     node-key="id"
                     highlight-current
                     default-expand-all
                     :props="{ label: 'categoryName' }"
                     :filter-node-method="filterNode"
                     :expand-on-click-node="false"
                     @node-click="handleNodeClick"
            >
                <template #default="{ node, data }">
                    <div class="flex w-full justify-between">
                        <el-tooltip :disabled="node.label.length < 8"
                                    effect="light"
                                    :content="node.label"
                                    placement="top"
                        >
                            <span class="text-ellipsis w-110 ws-nowrap of-hidden">{{ node.label }}</span>
                        </el-tooltip>

                        <span class="c-#DA0004">

                            <el-icon @click.stop="doEditMenu(data)">
                                <EditPen />
                            </el-icon>

                            <!-- 根节点不可删除 -->
                            <el-icon v-if="data.level !== 1"
                                     class="ml-10"
                                     @click.stop="doDelMenu(data)"
                            >
                                <Delete />
                            </el-icon>
                        </span>
                    </div>
                </template>
            </el-tree>
        </ElCard>

        <ElCard class="ml-20 min-h-539 w-80%">
            <template v-if="selected.level">
                <!-- 添加属性 -->
                <AddStats v-if="selected.level === 1"
                          ref="statsRef"
                          :data="selected.id"
                          @cancel="doCancel"
                />

                <!-- 清单列表 计算规则 -->
                <AddRule v-else
                         ref="ruleRef"
                         :data="selected.id"
                         @cancel="doCancel"
                />
            </template>

            <div v-else
                 class="c-#606266 lh-539 text-center"
            >
                请选择类目
            </div>
        </ElCard>
    </div>

    <!-- 类目新增编辑弹框 -->
    <PlusDialogForm v-model:visible="addDiglog"
                    v-model="addForm"
                    :title="isEdit ? '编辑' : '新增'"
                    width="500"
                    :form="{ columns: addCol, rules, labelWidth: 100 }"
                    @confirm="saveMenu"
    >
        <template #plus-field-parentId>
            <el-cascader ref="caderRef"
                         v-model="addForm.parentId"
                         class="w-full"
                         :disabled="isEdit"
                         :options="treeData"
                         :show-all-levels="false"
                         clearable
                         :props="{ expandTrigger: 'hover', label: 'categoryName', value: 'id', checkStrictly: true, emitPath: false }"
            />
        </template>
    </PlusDialogForm>
</template>

<style lang="scss" scoped></style>
